package bsf.http;

import bsf.base.BsfException;
import bsf.http.pool.HttpClientPoolManager;
import bsf.serialization.json.JsonProvider;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;

/**
 * Created by chejiangyi on 2017/3/31.
 */
public class HttpProvider {
    private static final String charset = "utf-8";//解决中文乱码问题

    public String postWithJson(String url, HashMap<String, Object> param) {
        try {
            HttpClient client = HttpClientPoolManager.GetPool().getClient();
            HttpPost post = new HttpPost(url);
            post.setHeader("Accept-Encoding", "gzip");	//gzip支持

            if (param.size() > 0) {
                String json = new JsonProvider().serialize(param);
                StringEntity entity = new StringEntity(json, charset);
                entity.setContentEncoding(charset);
                entity.setContentType("application/json");
                post.setEntity(entity);
            }
            HttpResponse response = client.execute(post);
            return tryToGzipDecompress(response);
        }
        catch(IOException exp)
        {
            throw new BsfException("postWithJson",exp,this.getClass());
        }
    }

    private String tryToGzipDecompress(HttpResponse response)
    {
        try {
            boolean isGzip = false;Header[] headers = response.getHeaders("Content-Encoding");
            if(headers!=null)//gzip 支持
            {
                for (int i = 0; i < headers.length; i++) {
                    if (headers[i].toString().toLowerCase().indexOf("gzip") > -1) {
                        isGzip = true;
                        break;
                    }
                }
            }
            if(isGzip==true) {
                return EntityUtils.toString(new GzipDecompressingEntity( response.getEntity()),charset);
            }
            else
            {   return EntityUtils.toString( response.getEntity(),charset);}
        }
        catch (IOException exp)
        {
            throw new BsfException("Gzip解压失败",exp,this.getClass());
        }

    }
}
